package com.ruitu.mall_98_2.mine;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.AppUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.MD5Util;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.view.IdentifyingCode;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.mall_98_2.mvp.contract.LoginContract;
import com.ruitu.mall_98_2.mvp.model.LoginModel;
import com.ruitu.mall_98_2.mvp.presenter.LoginPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.User;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.android.model.UserInfo;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class LoginActivity extends MyBaseActivity<LoginPresenter, LoginModel> implements LoginContract.View {
    private TextView tv_new_user_register;//注册
    private TextView tv_forget_password;//忘记密码
    private TextView tv_login;//登录
    private ImageView iv_password_visibility;//密码查看
    private EditText et_login_tel, et_login_password;//手机号密码
    private String tel, psw;

    private LinearLayout ll_weixin;
    private LinearLayout ll_qq;

    private ImageView iv_weixin;

    private String unionid;
    private String name;
    private String imageUrl;
    private String type;
    private String platformName;
    private AlertDialog alertDialog;
    private TextView tv_get_code;
    private EditText et_code;
    private boolean isGeting = true;
    private int time = 60;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void initViews() {
        super.initViews();
        tv_new_user_register = findViewById(R.id.tv_new_user_register);
        tv_forget_password = findViewById(R.id.tv_forget_password);
        et_login_tel = findViewById(R.id.et_login_tel);
        et_login_password = findViewById(R.id.et_login_password);
        iv_password_visibility = findViewById(R.id.iv_password_visibility);
        tv_login = findViewById(R.id.tv_login);
        ll_weixin = findViewById(R.id.ll_weixin);
        ll_qq = findViewById(R.id.ll_qq);
        String tel = Arad.preferences.getString("tel");
        String psw = Arad.preferences.getString("psw");
        if (!TextUtils.isEmpty(tel)) {
            et_login_tel.setText(tel);
            et_login_password.setText(psw);
            if (!TextUtils.isEmpty(psw)) {
                tv_login.setEnabled(true);
            }
        }
        setListener();

    }

    private void setListener() {
        tv_new_user_register.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);
        iv_password_visibility.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        ll_weixin.setOnClickListener(this);
        ll_qq.setOnClickListener(this);

        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(et_login_tel.getText()) &&
                        !TextUtils.isEmpty(et_login_password.getText())) {
                    tv_login.setEnabled(true);
                } else {
                    tv_login.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        et_login_tel.addTextChangedListener(textWatcher);
        et_login_password.addTextChangedListener(textWatcher);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (tv_new_user_register == v) {
            startActivity(RegistActivity.class);
        }

        if (tv_forget_password == v) {
            startActivity(ForgetPasswordActivity.class);
        }

        //查看密码/隐藏密码
        if (iv_password_visibility == v) {
            if (iv_password_visibility.isSelected()) {
                iv_password_visibility.setSelected(false);
                et_login_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                iv_password_visibility.setSelected(true);
                et_login_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
        }
        //登录
        if (tv_login == v) {
            tel = et_login_tel.getText().toString();
            psw = et_login_password.getText().toString();
            if (!TextUtils.isEmpty(tel)) {
                if (!TextUtils.isEmpty(psw)) {
                    showProgress();
                    mPresenter.login(tel, MD5Util.md5String(psw), "0", "");
                } else {
                    ToastUtils.showShort("密码不能为空");
                }
            } else {
                ToastUtils.showShort("用户名不能为空");
            }
        }

        if (ll_qq == v) {
            if (AppUtils.isInstallApp("com.tencent.mobileqq")) {
                //QQ的登录
                platformName = "QQ";
                setAuthorize(platformName);
                type = "0";
            } else {
                ToastUtils.showShort("您没有安装QQ");
            }

        }

        if (ll_weixin == v) {
            if (AppUtils.isInstallApp("com.tencent.mm")) {
                //微信的登录
                platformName = "Wechat";
                setAuthorize(platformName);
                //第三方登录的类型
                type = "1";
            } else {
                ToastUtils.showShort("您没有安装微信");
            }
        }
    }

    @Override
    public void loginSuc(User user) {
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        Arad.preferences.putString("tel", tel).flush();
        Arad.preferences.putString("psw", psw).flush();
        AppHolder.instance().setUser(user);
        Arad.bus.post(new EventModel(18110900));
        finish();
    }

    @Override
    public void thirdLoginSuc(User user) {
        Arad.preferences.putString("openId", unionid).flush();
        Arad.preferences.putString("type", type).flush();
        AppHolder.instance().setUser(user);
        Arad.bus.post(new EventModel(18110900));
        finish();
    }

    @Override
    public void setThird() {
        Intent intent = new Intent(LoginActivity.this, RelevanceTelActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("imageUrl", imageUrl);
        intent.putExtra("unionid", unionid);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    @Override
    public void differentPlace() {
        showVerificationDialog();
    }

    //第三方登录传的应用名
    public void setAuthorize(String platform) {
        hideProgress();
        showProgress();
        if (!JShareInterface.isAuthorize(platform)) {
            JShareInterface.authorize(platform, mAuthListener);
        } else {
            JShareInterface.removeAuthorize(platform, mAuthListener);
        }
    }

    //第三方登录的监听
    AuthListener mAuthListener = new AuthListener() {
        @Override
        public void onComplete(Platform platform, int i, BaseResponseInfo data) {
            hideProgress();
            String toastMsg = null;
            switch (i) {
                case Platform.ACTION_AUTHORIZING:
                    if (data instanceof AccessTokenInfo) {        //授权信息
                        String token = ((AccessTokenInfo) data).getToken();//token
                        long expiration = ((AccessTokenInfo) data).getExpiresIn();//token有效时间，时间戳
                        String refresh_token = ((AccessTokenInfo) data).getRefeshToken();//refresh_token
                        String openid = ((AccessTokenInfo) data).getOpenid();//openid
                        //授权原始数据，开发者可自行处理
                        String originData = data.getOriginData();

                    }
                    handler.sendEmptyMessage(979);
                    break;

                case Platform.ACTION_REMOVE_AUTHORIZING:
                    toastMsg = "删除授权成功";
                    break;
                case Platform.ACTION_USER_INFO:
                    if (data instanceof UserInfo) {      //第三方个人信息
                        String openid = ((UserInfo) data).getOpenid();  //openid
                        name = ((UserInfo) data).getName();  //昵称
                        imageUrl = ((UserInfo) data).getImageUrl();  //头像url
                        int gender = ((UserInfo) data).getGender();//性别, 1表示男性；2表示女性
                        //个人信息原始数据，开发者可自行处理
                        String originData = data.getOriginData();
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(originData);
                            unionid = (String) jsonObject.get("unionid");
                            Logg.i("unionid: " + unionid);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (type.equals("0")) {
                            unionid = openid;
                            Logg.i("openId:" + openid);
                        } else {

                            try {
                                jsonObject = new JSONObject(originData);
                                unionid = (String) jsonObject.get("unionid");
                                if (TextUtils.isEmpty(unionid)) {
                                    unionid = openid;
                                }
                                Logg.i("Unionid :" + unionid);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
//                        showProgress();
                        mPresenter.quickLogin(unionid, type);
                    }
                    break;
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            hideProgress();
            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    toastMsg = "授权失败";
                    break;
                case Platform.ACTION_REMOVE_AUTHORIZING:
                    toastMsg = "删除授权失败";
                    break;
                case Platform.ACTION_USER_INFO:
                    toastMsg = "获取个人信息失败";
                    break;
            }
            if (handler != null) {
                Message msg = handler.obtainMessage(1);
                msg.obj = toastMsg + (error != null ? error.getMessage() : "") + "-" + errorCode;
                msg.sendToTarget();
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            hideProgress();
            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    toastMsg = "取消授权";
                    break;
                // TODO: 2017/6/23 删除授权不存在取消
                case Platform.ACTION_REMOVE_AUTHORIZING:
                    break;
                case Platform.ACTION_USER_INFO:
                    toastMsg = "取消获取个人信息";
                    break;
            }
            if (handler != null) {
                Message msg = handler.obtainMessage(1);
                msg.obj = toastMsg;
                msg.sendToTarget();
            }
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 979) {
                JShareInterface.getUserInfo(platformName, mAuthListener);
            }

            if (msg.what == 999) {
                if (isGeting) {
                    setGetCodeTime(--time);
                    handler.sendEmptyMessageDelayed(999, 1000);
                }
            }

        }
    };

    private void setGetCodeTime(int time) {
        if (time == 0) {
            isGeting = false;
            tv_get_code.setEnabled(true);
            tv_get_code.setText("获取验证码");
            this.time = 60;
        } else {
            tv_get_code.setText(time + "s后重新获取");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setBus(EventModel eventModel) {
        if (eventModel.getEventCode() == 18113000) {
            finish();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    private ImageView iv_verifactiion_code;

    private void showVerificationDialog() {
        alertDialog = new AlertDialog.Builder(this).create();
        View view = View.inflate(this, R.layout.item_yue_pay_dialog, null);
        if (alertDialog != null) {
            alertDialog.setView(view);
        }
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        TextView tv_cancle = view.findViewById(R.id.tv_cancle);
        TextView tv_dialog_type = view.findViewById(R.id.tv_dialog_type);
        tv_dialog_type.setText("请输入验证码进行登录");
        tv_get_code = view.findViewById(R.id.tv_get_code);
        TextView tv_tel = view.findViewById(R.id.tv_tel);
        et_code = view.findViewById(R.id.et_code);
        final EditText et_iv_verifactiion_code = view.findViewById(R.id.et_iv_verifactiion_code);
        iv_verifactiion_code = view.findViewById(R.id.iv_verifactiion_code);
        tv_tel.setText("验证码将发送到" + tel + "请注意查收");
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = et_code.getText().toString();
                if (TextUtils.isEmpty(s)) {
                    ToastUtils.showShort("验证码不能为空");
                } else {
                    showProgress();
                    mPresenter.login(tel, MD5Util.md5String(psw), "2", et_code.getText().toString());
                }
            }
        });
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
//                stopHandler();
                handler.removeMessages(999);
                time = 60;
            }
        });

        tv_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals(et_iv_verifactiion_code.getText().toString().toLowerCase(), resultCode)) {
                    tv_get_code.setEnabled(false);
                    setGetCodeTime(60);
                    isGeting = true;
//                et_code.setText(baseResult.getData().toString());
                    handler.sendEmptyMessageDelayed(999, 1000);
                    getCode();
                } else {
                    ToastUtils.showShort("图片验证不正确");
                }
                getVerifactionCode();
            }
        });

        iv_verifactiion_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVerifactionCode();
            }
        });
        alertDialog.show();
        getVerifactionCode();
    }

    private String resultCode;

    private void getVerifactionCode() {
        iv_verifactiion_code.setImageBitmap(IdentifyingCode.getInstance().createBitmap());
        resultCode = IdentifyingCode.getInstance().getCode().toLowerCase();
    }

    private void getCode() {
        APIRetrofit.getDefault().smsSend(tel, "8")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showShort("获取验证码失败");
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            ToastUtils.showShort(baseResult.getMsg());

                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                });

    }
}
